<template>
  <Page title="课堂导学" :on-page-back="onPageBack">
    <template #navBarCustom>
      <view class=""></view>
    </template>
    <template #content>
      <div class="w-full h-full px-20px box-border flex flex-col">
        <!-- 学科列表 -->
        <subject-tabs
          class="py-16px"
          :tabs="subjects.list"
          :active="subjects.active"
          @change="subjects.onChange($event)"
        />
        <!-- 课堂导学列表 -->
        <scroll-view
          ref="scroll"
          class="flex-1 overflow-scroll"
          :refresher-enabled="true"
          :refresher-loader-offset-y="-16"
          @scrolltolower="guidances.getList(subjects.active)"
          @refresh="guidances.refresh($event)"
        >
          <guidance-list :list="guidances.list" @todo="guidances.todo($event)" />
          <load-more
            cssStyle="padding-top:0.14rem"
            :loading="guidances.loading"
            :has-more="guidances.hasMore"
            @click="guidances.getList(subjects.active)"
          />
        </scroll-view>
      </div>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/page'
import SubjectTabs from '@/components/subject/tabs'
import ScrollView from '@/components/scroll-view'
import GuidanceList from './components/guidance-list'
import LoadMore from '@/components/load-more'
import { getClassGuidanceSubjectApi, getClassGuidanceListApi } from '@/api/class-guidance'
import { mapActions } from 'vuex'
import { debounce } from '@/utils'
import { MODULE_ID } from '@/store/modules/module-use'

export default {
  components: {
    Page,
    ScrollView,
    SubjectTabs,
    GuidanceList,
    LoadMore
  },
  data() {
    return {
      loading: null,
      guidanceIds: {},
      storageGuidanceIds: {},
      lastGuidanceId: '',
      // 学科栏目
      subjects: {
        vm: this._self,
        active: '',
        list: [],
        getList: async function (callback) {
          const { data = [] } = await getClassGuidanceSubjectApi()
          const subjects = await this.vm.getDictByType('subject')

          const list = []
          data.forEach((i) => {
            const subject = subjects.find((s) => s.value == i)
            list.push({
              dictType: 'subject',
              label: subject.label,
              status: 0,
              value: subject.value
            })
          })

          // 如果没有开通的科目，弹出弹窗
          if (list.length === 0) {
            this.vm.$popup.show({
              type: 'alert',
              success: (popup) => {
                popup.$on('confirm', () => {
                  this.vm.$popup.hide('alert')
                  this.vm.$router.back()
                })
                popup.setData({
                  content: '没有已开通的科目'
                })
              }
            })
            return
          }

          list.unshift({
            dictType: 'subject',
            label: '全部',
            status: 0,
            value: ''
          })

          this.list = list.map((item) => {
            const { value: subjectId } = item
            subjectId &&
              this.vm.$storage.class_guidance
                .getGuidanceIdsItem(subjectId)
                .then(({ success, data }) => {
                  success && (this.vm.storageGuidanceIds[subjectId] = data)
                })
            return item
          })
          callback('')
        },
        onChange: debounce(function (subjectId) {
          // 上传模块使用时间
          this.vm.$store.state.moduleUse.currentModuleUse.submit()
          // 重置
          this.vm.$store.state.moduleUse.currentModuleUse.onSubjectChange(subjectId)

          this.active = subjectId
          this.vm.guidances.reset()
          this.vm.guidances.getList(subjectId)
        }, 300)
      },
      // 课堂导学列表
      guidances: {
        vm: this._self,
        pageNo: 1,
        pageSize: 12,
        loading: true,
        hasMore: true,
        list: [],
        getList: async function (subjectId) {
          if (this.loading) return

          this.loading = true
          const guidances = this.list

          let params = {
            pageNo: this.pageNo,
            pageSize: this.pageSize
          }

          if (subjectId) params['subject'] = subjectId

          const {
            data: { list }
          } = await getClassGuidanceListApi(params)

          if (list.length < this.pageSize) {
            this.hasMore = false
          }

          if (list.length > 0) {
            if (this.pageNo === 1 && !subjectId) {
              this.vm.lastGuidanceId = list[0].id
            }

            const { guidanceIds } = this.vm

            guidances.push(
              ...list.map((item) => {
                const currentSubjectId = this.vm.subjects.active
                const { subject: subjectId, id: guidanceId } = item
                const storage_guidance_ids_item = this.vm.storageGuidanceIds[currentSubjectId]

                // 标记是否已读
                if (!currentSubjectId) {
                  item['unread'] = 1
                  for (let subjectId in this.vm.storageGuidanceIds) {
                    if (this.vm.storageGuidanceIds[subjectId].find((id) => id === guidanceId)) {
                      item['unread'] = 0
                      break
                    }
                  }
                } else if (
                  storage_guidance_ids_item &&
                  storage_guidance_ids_item.find((id) => id === guidanceId)
                ) {
                  item['unread'] = 0
                } else {
                  item['unread'] = 1
                }

                // 缓存id
                if (guidanceIds[subjectId]) {
                  const guidance_ids = guidanceIds[subjectId]
                  guidanceIds[subjectId] = Array.from(new Set(guidance_ids.concat(guidanceId)))
                } else {
                  guidanceIds[subjectId] = [guidanceId]
                }

                return item
              })
            )
            this.pageNo++
          }

          this.loading = false
        },
        refresh: async function (done = () => {}) {
          const currentSubjectId = this.vm.subjects.active
          const params = {
            pageNo: (this.pageNo = 1),
            pageSize: this.pageSize,
            subject: currentSubjectId ? currentSubjectId : undefined
          }

          const {
            data: { list }
          } = await getClassGuidanceListApi(params)

          this.list.length = 0
          this.list.push(
            ...list.map((item) => {
              const { guidanceIds } = this.vm
              const { subject: subjectId, id: guidanceId } = item
              const storage_guidance_ids_item = this.vm.storageGuidanceIds[currentSubjectId]

              // 标记是否已读
              if (!currentSubjectId) {
                item['unread'] = 1
                for (let subjectId in this.vm.storageGuidanceIds) {
                  if (this.vm.storageGuidanceIds[subjectId].find((id) => id === guidanceId)) {
                    item['unread'] = 0
                    break
                  }
                }
              } else if (
                storage_guidance_ids_item &&
                storage_guidance_ids_item.find((id) => id === guidanceId)
              ) {
                item['unread'] = 0
              } else {
                item['unread'] = 1
              }

              // 缓存id
              if (guidanceIds[subjectId]) {
                const guidance_ids = guidanceIds[subjectId]
                guidanceIds[subjectId] = Array.from(new Set(guidance_ids.concat(guidanceId)))
              } else {
                guidanceIds[subjectId] = [guidanceId]
              }

              return item
            })
          )
          this.pageNo++

          done()
        },
        reset: function () {
          this.pageNo = 1
          this.pageSize = 12
          this.loading = false
          this.hasMore = true
          this.list = []
        },
        todo: async function (item) {
          const { beginTime } = item

          if (beginTime) {
            const beginTimestamp = new Date(beginTime).getTime()
            const nowTime = new Date().getTime()

            if (nowTime < beginTimestamp) {
              this.vm.$message.error('未到发布时间')
              return
            }
          }

          this.vm.$router.push(`/pages/class-guidance/detail?id=${item.id}`)
        }
      }
    }
  },
  computed: {},
  mounted() {
    this.$store.dispatch('initClassGuidanceStorage')
    this.subjects.getList((subjectId) => {
      this.guidances.loading = false
      this.guidances.getList(subjectId)

      // 初始化模块使用记录
      this.$store.commit('setCurrentModuleUse', {
        vm: this._self,
        type: MODULE_ID.CLASS_GUIDANCE,
        subjectId
      })
    })
  },
  methods: {
    ...mapActions(['getDictByType']),
    onPageBack() {
      // 缓存作业id
      this.saveStorageGuidanceIds()
      // 发送最新的课堂导学id给安卓
      if (window.android && this.lastGuidanceId) {
        window.android.setLastClassGuidanceId(this.lastGuidanceId)
      }
      this.$router.back()
    },
    saveStorageGuidanceIds() {
      // 缓存guidanceIds
      const { guidanceIds, storageGuidanceIds } = this
      const newGuidanceIds = {}

      for (let subjectId in guidanceIds) {
        newGuidanceIds[subjectId] = guidanceIds[subjectId]
      }

      for (let subjectId in storageGuidanceIds) {
        if (newGuidanceIds[subjectId]) {
          const ids = newGuidanceIds[subjectId]
          newGuidanceIds[subjectId] = Array.from(new Set(storageGuidanceIds[subjectId].concat(ids)))
        } else {
          newGuidanceIds[subjectId] = storageGuidanceIds[subjectId]
        }
      }

      for (let subjectId in newGuidanceIds) {
        this.$storage.class_guidance.getGuidanceIdsItem(subjectId).then(({ success }) => {
          if (success) {
            this.$storage.class_guidance.putGuidanceIdsItem({
              subjectId,
              value: newGuidanceIds[subjectId]
            })
          } else {
            this.$storage.class_guidance.setGuidanceIdsItem({
              subjectId,
              value: newGuidanceIds[subjectId]
            })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
